package com.ltu.controller.customize;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.logging.log4j.core.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ltu.ai.sparkdesk.websocket.AiContextManager;
import com.ltu.config.shiro.ShiroUtil;
import com.ltu.config.shiro.dto.UserDto;
import com.ltu.domain.mp_entity.customize.DeviceAdEntity;
import com.ltu.domain.mp_entity.customize.DeviceEntity;
import com.ltu.domain.mp_entity.customize.PushAdEntity;
import com.ltu.mapper.customize.DeviceAdMapper;
import com.ltu.model.request.base.BaseFilterPageReq;
import com.ltu.model.request.base.BaseIdReq;
import com.ltu.model.response.base.CodeDataResp;
import com.ltu.service.customize.DeviceService;
import com.ltu.service.customize.PushAdService;
import com.ltu.service.impl.BaseServiceImpl;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;


/**
 * <p>
 * 广告 前端控制器
 * </p>
 *
 * @author 若尘
 * @since 2024-09-26
 */
@RestController

@RequestMapping("/DeviceAd")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Api(tags= "广告")
public class DeviceAdController extends BaseServiceImpl<DeviceAdMapper, DeviceAdEntity>{
	private final PushAdService pushAdService;
	private final DeviceService deviceService;
	private final AiContextManager aiContextManager;
	
	
    @ApiOperation(value="获取分页列表")
    @RequestMapping(value="/getMePage", method= RequestMethod.POST)
    public CodeDataResp<Page<DeviceAdEntity>> getMePage(@RequestBody  BaseFilterPageReq<DeviceAdEntity> req ) {
    	return super.getMePage(req);
    }
    
    @ApiOperation(value="获取列表")
    @RequestMapping(value="/getList", method= RequestMethod.POST)
    public CodeDataResp<List<DeviceAdEntity>> getList(@RequestBody  BaseFilterPageReq<DeviceAdEntity> req ) {
        return super.getMeList(req);
    }

    @ApiOperation(value="新增/保存")
    @RequestMapping(value="/edit", method= RequestMethod.POST)
    public CodeDataResp edit(@RequestBody DeviceAdEntity req) {
        return super.edit(req);
    }
    
    @ApiOperation(value="投放广告")
    @RequestMapping(value="/put-ad", method= RequestMethod.POST)
    public CodeDataResp edits(@RequestBody DeviceAdEntity param ) {
    	Assert.requireNonEmpty(param.getId(), "广告ID必传");
    	DeviceAdEntity req = this.getById(param.getId());
    	req.setDeviceIds(param.getDeviceIds());
    	// 获取指定设备下的广告记录，存在则修改，否则新增记录
    	QueryWrapper<PushAdEntity> qw = new QueryWrapper<PushAdEntity>();
    	qw.lambda().eq(PushAdEntity :: getAdId, param.getId())
    				.in(PushAdEntity :: getDeviceId,param.getDeviceIds());
    	List<PushAdEntity> olds = this.pushAdService.list(qw);
    	Map<Integer,PushAdEntity>  mps = new HashMap<Integer, PushAdEntity>(olds.size());    	
    	if(CollectionUtils.isNotEmpty(olds)) 
    		mps = olds.stream().collect(Collectors.toMap(PushAdEntity :: getDeviceId, a -> a,(o,n) -> o));
    	List<DeviceEntity> devices =  this.deviceService.listByIds( req.getDeviceIds());
    	Assert.requireNonEmpty(devices, "未添加设备");
    	Integer adId = Integer.parseInt(req.getId());
    	UserDto  operatory =  ShiroUtil.getPrincipalUser();
    	Integer  updator = Integer.parseInt(  operatory.getId());
    	List<PushAdEntity>  addOrEdits = new ArrayList<PushAdEntity>( devices.size());
    	List<String> deviceMacs = new ArrayList<String>();
    	for (DeviceEntity item  :devices) {
    		PushAdEntity  temp = new PushAdEntity();
    		Integer deviceId = Integer.parseInt(item.getId());
    		if(mps.containsKey( deviceId))
    			temp = mps.get(deviceId);
    		temp.setAdId(adId)
    			.setAdName(req.getAdName())
    			.setAdUrl(req.getAdUrl())
    			.setCreateUser(operatory.getUsername())
    			.setDeviceId(deviceId)
    			.setDeviceMac(item.getDeviceNo())
    			.setDeviceName(item.getDeviceName())
    			.setUpdator(updator);
    		addOrEdits.add(temp);
    		deviceMacs.add(item.getDeviceNo());
		}
    	this.pushAdService.saveOrUpdateBatch(addOrEdits);
    	//通过websocket给指定设备传输广告的视频文件地址 视频文件的访问关闭访问鉴权
    	aiContextManager.pushAd(deviceMacs);
    	
    	return   CodeDataResp.valueOfSuccessEmptyData();
    }
    
//    @ApiOperation(value="批量修改数据")
//    @RequestMapping(value="/edits", method= RequestMethod.POST)
    public CodeDataResp edits(@RequestBody List<DeviceAdEntity> reqs) {
    	super.saveOrUpdateBatch(reqs);
    	return   CodeDataResp.valueOfSuccessEmptyData();
    }
    
    
    @ApiOperation(value="获取详情")
    @RequestMapping(value="/getDetail/{id}", method= RequestMethod.GET)
    public CodeDataResp<DeviceAdEntity> getDetail(@PathVariable String id) {
 		BaseIdReq req=new BaseIdReq(id);
        return super.getDetail(req);
    }
    

 	 @ApiOperation(value="删除")
     @RequestMapping(value="/remove/{id}", method= RequestMethod.GET)
     public CodeDataResp remove(@PathVariable String id) {
       	QueryWrapper<PushAdEntity>   qw = new QueryWrapper<PushAdEntity>();
     	qw.lambda().eq(PushAdEntity :: getAdId, id);
     	List<PushAdEntity>  list = pushAdService.list(qw);
     	 super.removeById(id);
     	if(!CollectionUtils.isEmpty(list)) {
     		List<Integer> ids = list.stream().map(a -> Integer.parseInt(a.getId())).distinct().collect(Collectors.toList());
     		pushAdService.removeByIds(ids );
     		List<String> deviceMacs = list.stream().map( a -> a.getDeviceMac()).distinct().collect(Collectors.toList());
     		aiContextManager.pushAd(deviceMacs);
     	}
     	 
    	// TODO Auto-generated method stub
		return CodeDataResp.valueOfSuccessEmptyData();
     }
 	 
     
 //   @ApiOperation(value="删除s")
//    @RequestMapping(value="/removes", method= RequestMethod.POST)
    public CodeDataResp removes(@RequestBody List<Integer> ids) {
    		super.removeByIds(ids);
        return CodeDataResp.valueOfSuccessEmptyData();
    }

}

